//
//  AlbumListController.m
//  XMMusicTest
//
//  Created by sfk-ios on 2017/12/22.
//  Copyright © 2017年 sfk-JasonSu. All rights reserved.
//

#import "AlbumListController.h"
#import "XMSearchMusicModel.h"

@interface AlbumListController ()<UIActionSheetDelegate>
@property (strong, nonatomic) NSMutableArray *dataArray;
@end

@implementation AlbumListController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationController.navigationBar.tintColor = [UIColor orangeColor];
    self.navigationItem.title = @"我的收藏";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(dismissSelf)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(showActionSheet)];
    
    self.tableView.rowHeight = 50;
    self.tableView.tableFooterView = [UIView new];
    
    // 歌单中的歌曲数据
    NSArray *array = [XMSearchMusicModel bg_find:DEFAULT_TABLE_NAME where:nil];
    self.dataArray = [NSMutableArray arrayWithArray:array];
    if (self.dataArray.count == 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD showSingleMessage:@"暂无收藏歌曲~"];
        });
    }
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *albumCellID = @"albumCellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:albumCellID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:albumCellID];
        //        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
        cell.detailTextLabel.textColor = [UIColor grayColor];
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
    }
    
    XMSearchMusicModel *song = self.dataArray[indexPath.row];
    // 缩略图
    NSString *imgStr = song.album[@"coverSmall"];
    NSString *albumName = song.album[@"name"];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:imgStr?:@""] placeholderImage:[UIImage imageNamed:@"nomssg_icon"]];
    // 歌曲名
    cell.textLabel.text = song.name;
    // 歌手
    NSDictionary *artists = song.artists.firstObject;
    NSString *singerName = artists[@"name"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ - %@",singerName,albumName];
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"==%@",self.dataArray[indexPath.row]);
    
    [[NSNotificationCenter defaultCenter]postNotificationName:NOTI_PLAY_ALBUM object:self.dataArray userInfo:@{@"indexRow" : [NSString stringWithFormat:@"%ld",indexPath.row]}];
    
    [self.tableView reloadData];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissSelf];
    });
}

//以下是添加删除功能的代码
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewRowAction *layTopRowAction1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        XMSearchMusicModel *song = self.dataArray[indexPath.row];
        
        NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(song.ID)];
        [XMSearchMusicModel bg_delete:DEFAULT_TABLE_NAME where:where];
        
        /// 数据删除
        [self.dataArray removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        // 如果删除section调用上面的方法会崩溃，因为删除了某个section的某一个row，但是section却没有被删除，系统就会发生UI崩溃。
        //        [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
        
        //        [self.tableView reloadData];
        
        //[tableView setEditing:YES animated:YES];
        
    }];
    layTopRowAction1.backgroundColor = [UIColor redColor];
    
    NSArray *arr = @[layTopRowAction1];
    return arr;
    
}


#pragma mark - 事件处理

- (void)dismissSelf
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)showActionSheet
{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除全部收藏歌曲" otherButtonTitles:nil, nil];
    
    [sheet showInView:self.view.window];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"buttonIndex===%ld",buttonIndex);
    
    if (buttonIndex == 0) { // 删除全部
        
        [self.dataArray removeAllObjects];
        /**
         清除表的所有数据.
         */
        [XMSearchMusicModel bg_clear:DEFAULT_TABLE_NAME];
        
        [self.tableView reloadData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD showSingleMessage:@"已清空收藏列表"];
        });
    }
}

@end
